using AutoMapper;
using microsoft_TODO.DTOs;
using microsoft_TODO.Models;
using microsoft_TODO.MongoCore;
using microsoft_TODO.ServiceCore;
using Microsoft.AspNetCore.Identity;
using System;

namespace microsoft_TODO.ServiceCore.Services {
    public class UserService : IUserService {
        IUserRepository _userRepository;
        IListRepository _listRepository;
        IMapper _mapper;

        public UserService (
            IUserRepository userRepository,
            IListRepository listRepository,
            IMapper mapper) {
            _userRepository = userRepository;
            _listRepository = listRepository;
            _mapper = mapper;
        }

        public User Authenticate (LoginDto dto) {
            var entity = _userRepository.FirstOrDefault(u => u.Username == dto.Username);
            if (entity == null)
                return null;

            var hasher = new PasswordHasher<User> ();
            var result = hasher.VerifyHashedPassword (entity, entity.Password, dto.Password);
            if (result == PasswordVerificationResult.Failed)
                return null;

            return entity;
        }

        public bool CreateUser (RegisterDto dto) {
            var entity = _mapper.Map<User> (dto);
            var hasher = new PasswordHasher<User> ();
            entity.Password = hasher.HashPassword (entity, entity.Password);
            var back = _userRepository.Insert (entity);
            if (string.IsNullOrEmpty(back.Id))
                return false;
            // 插入默认LIST - To-Do
            var listEntity = new CheckList<Task>{
                Title = "To-Do",
                Icon = "todo",
                ZIndex = 0,
                IsStatic = true,
                UserId = back.Id,
                Tasks = new System.Collections.Generic.List<Task>()
            };
            var backList = _listRepository.Insert(listEntity);
            return !string.IsNullOrEmpty (backList.Id);
        }

        public bool IsUsernameExistent (string username) {
            return _userRepository.IsExistent(u => u.Username == username);
        }
    }
}